import { defineStore } from "pinia";
import $axios from '../utils/axios';

export const useMyactivityStore = defineStore("myactivity", {
    state: () => {
        return {
            allData: [],
            canceledData: [],
            futureData: [],
            updateForm: {},
            UserList: [],
            dialogVisible: false,
            aId: -1,
            activityName: '',
            dialogTitle: '',
        }
    },
    actions: {
        async init() {
            const user = JSON.parse(sessionStorage.getItem("user"))
            const path = '/userActivity/selectAllByuId/' + user.id
            const { data: res } = await $axios.get(path)
            if (res.code === 200) {
                this.allData = res.result
                console.log(this.allData);
            }
        },
        async getFutureData() {
            const user = JSON.parse(sessionStorage.getItem("user"))
            const path = '/userActivity/selectByUIdByState/' + user.id + '/' + '未开始'
            const { data: res } = await $axios.get(path)
            if (res.code === 200) {
                this.futureData = res.result
                console.log(this.futureData);
            }
        },
        async getCanceledData() {
            const user = JSON.parse(sessionStorage.getItem("user"))
            const path = '/userActivity/selectByUIdBymyState/' + user.id + '/' + '已取消报名'
            const { data: res } = await $axios.get(path)
            if (res.code === 200) {
                this.canceledData = res.result
                console.log(this.canceledData);
            }
        },
        async update(index, row) {
            this.updateForm.id = row.id
            this.updateForm.state = '已取消报名'
            console.log(this.updateForm);
            const path = '/userActivity/update'
            const { data: res } = await $axios.post(path, this.updateForm)
            if (res.code === 200) {
                this.init()
                this.getFutureData()
                this.getCanceledData()
            } else {
                ElMessage.error('Oops, this is a error message.')
            }
        },
        pre4UserList(index, row) {
            this.dialogVisible = true
            this.activityName = row.activityDate + "\"" + row.activityName + "\""
            this.dialogTitle = this.activityName + "报名人员统计表"
            this.aId = row.id
            console.log(this.dialogTitle);
            this.getUserList(row.id)
        },
        async getUserList(aId) {
            // console.log(this.aId)
            const path = '/userActivity/selectUserByaId/' + aId
            const { data: res } = await $axios.get(path)
            if (res.code === 200) {
                this.UserList = res.result
                console.log(this.UserList);
            }
            else {
                this.UserList == res.result
            }
        },
        async download() {
            try {
                const path = '/download/excel/' + this.aId; // 新的URL路径  
                // const formData = new FormData(); // 如果需要发送文件或其他表单数据，可以使用FormData  
                // // 假设UserList是数组或者对象，直接发送  
                // formData.append('userList', JSON.stringify(this.UserList)); // 将UserList序列化为JSON字符串并发送  

                const response = await $axios.post(path, {
                    responseType: 'blob', // 设置响应类型为blob，以便处理二进制数据  
                });
                console.log(response);

                // 检查响应状态，假设API返回的是常见的code和data结构  
                if (response.status === 200) {
                    // 创建一个 Blob 对象来表示数据  
                    const blob = new Blob([response.data], { type: 'application/vnd.ms-excel;charset=utf-8' });

                    let downloadElement = document.createElement('a');
                    let href = window.URL.createObjectURL(blob); //创建下载的链接
                    downloadElement.href = href;
                    downloadElement.download = this.dialogTitle + '.xlsx'; //下载后文件名
                    document.body.appendChild(downloadElement);
                    downloadElement.click(); //点击下载
                    document.body.removeChild(downloadElement); //下载完成移除元素
                    window.URL.revokeObjectURL(href); //释放掉blob对象

                    // // 创建一个链接元素  
                    // const url = window.URL.createObjectURL(blob);
                    // const link = document.createElement('a');
                    // link.href = url;

                    // // 设置文件名  
                    // const filename = this.dialogTitle + '.xlsx';
                    // link.setAttribute('download', filename);

                    // // 触发下载  
                    // document.body.appendChild(link);
                    // link.click();

                    // // 清理  
                    // window.URL.revokeObjectURL(url);
                    // document.body.removeChild(link);

                    // console.log("下载成功");
                } else {
                    // 处理错误  
                    console.error("下载失败", response);
                }
            } catch (error) {
                // 捕获并处理任何异常  
                console.error("下载过程中发生错误：", error);
                // 如果你想在前端显示错误信息，可以使用UI库的方法（比如Vue中的this.$message.error）  
                // 但是由于你使用了async函数，这里的this可能不再是Vue实例，所以你需要确保正确引用this  
                // this.$message.error(error.message || error); // 假设你有一个全局的$message方法  
            }
        }
    }
})